package com.gitee.bluebird;

import com.google.protobuf.Message;
import io.netty.channel.ChannelHandlerContext;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public abstract class AbstractCommand<T extends Message> implements Command {
    private Class<?> clazz;

    public AbstractCommand() {
        clazz = ClazzUtil.find0(this, AbstractCommand.class, "T");
        if (clazz == null || clazz.equals(Object.class)) {
            throw new RuntimeException("not exist clazz:" + this.getClass().getName());
        }

    }

    @Override
    public void execute(ChannelHandlerContext ctx, Packet packet) {
        try {
            Method method = clazz.getMethod("parseFrom", byte[].class);
            T message = (T) method.invoke(null, packet.getBody());
            exec0(ctx, message);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }


    protected abstract void exec0(ChannelHandlerContext ctx, T message);
}
